package com.zany.util.xml;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import com.zany.util.ZanyErrorMsg;
import com.zany.util.ZanyException;
import com.zany.util.date.DateFormater;

public class XMLUtil {
	
	
	public String BuildXMLDoc(Map<String, Object> headerMap, List<Map<String, String>> bodyList) throws IOException, JDOMException {
		Element transaction = new Element("transaction");
		Document Doc = new Document(transaction);
		Element header = new Element("header");
		header = commPak("header",headerMap);
		transaction.addContent(header);
		Element body = new Element("body");
		for(Map<String, String> map :bodyList){
			Element result = new Element("result");
			result = commPak("result",map);
			body.addContent(result);
		}
		Element count = new Element("count");
		count.setText(bodyList.size()+"");
		body.addContent(count);
		transaction.addContent(body);
		String xml = xml2String(Doc);
		return xml;
	}
	
	public String BuildXMLDoc(Map<String, Object> headerMap, Map<String, String> bodyMap) throws IOException, JDOMException {
		Element transaction = new Element("transaction");
		Document Doc = new Document(transaction);
		Element header = new Element("header");
		header = commPak("header",headerMap);
		transaction.addContent(header);
		Element body = new Element("body");
		body = commPak("body",bodyMap);
		transaction.addContent(body);
		String xml = xml2String(Doc);
		return xml;
	}
	
	public String xml2String(Document xmlDoc){
        XMLOutputter otpt = new XMLOutputter();
        StringWriter out = new StringWriter();
        try {
            Format fmt = Format.getRawFormat();
            fmt.setEncoding("UTF-8");
            otpt.setFormat(fmt);
            otpt.output(xmlDoc, out);
            out.close();
        } catch (Exception e) {
            
        }
        return out.toString();
    }
	
	public static void main(String[] args) {
		System.out.println("HOUSE00101".substring(0, 9));
	}

	/**
     * 把Map结构的数据打包到Xml包中去.
     *
     * @param prvKey
     *            打包的Xml节点名
     * @param prvMap
     *            打包的Xml节点数据
     * @return Xml结点Element
     */

    public Element commPak(String prvKey, Map prvMap) {
        Element elem = new Element(prvKey);

        // 如果没有子节点,则置" ",以便GAPS平台阅读
        if (prvMap == null || prvMap.isEmpty()) {
            elem.setText(" ");
        }
        Iterator it = prvMap.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            Object prvObj = prvMap.get(key);
            if (prvObj != null) {
                if (prvObj instanceof String) {
                    String prvStr = (String) prvObj;
                    if (prvStr.equals("")) {
                        elem.addContent(new Element(key).setText(" "));
                    } else {
                        elem.addContent(new Element(key).setText(prvStr));
                    }
                } else if (prvObj instanceof HashMap) {
                    Element elemChild = commPak(key, (HashMap) prvObj);
                    elem.addContent(elemChild);
                }
            } else {
                elem.addContent(new Element(key).setText(" "));
            }
        }
        return elem;
    }
    
    public Map getNodeMapHeader(String buf) throws ZanyException {
    	Document xmlDoc = null; // 组装好的，或者解析出来的完整的xml文档

         Element transaction = null; // 文档的根节点
    	try {
        	SAXBuilder sb = new SAXBuilder();
            xmlDoc = sb.build(new StringReader(buf));
            transaction = xmlDoc.getRootElement();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ZanyException(ZanyErrorMsg.ERR_DEFAULT, "返回报文转化成xml文档失败！\n"+e.getMessage(),e);
        }
        Element tmpEle = null, parentEme = null, eMxUnit = null, childEme = null;
        Map tmpMap = tmpMap = new HashMap();;
        tmpEle = transaction;
        parentEme = tmpEle.getChild("header");
        List tmpList = parentEme.getChildren();
        if ((tmpList != null) && (!tmpList.isEmpty())) {
        	for (int i = 0; i < tmpList.size(); i++) {
        		eMxUnit = (Element) tmpList.get(i);
        		List child = eMxUnit.getChildren();
        		if ((child != null) && (!child.isEmpty())) {
        			for (int j = 0; j < child.size(); j++) {
        				childEme = (Element) child.get(j);
        				String name = childEme.getName();
        				String value = childEme.getText();
        				tmpMap.put(name, value);
        			}
        		}
        	}
        }
        return tmpMap;
	 }
	
	public Map getNodeMapBody(String buf) throws ZanyException {
		Document xmlDoc = null; // 组装好的，或者解析出来的完整的xml文档

	    Element transaction = null; // 文档的根节点
		try {
        	SAXBuilder sb = new SAXBuilder();
            xmlDoc = sb.build(new StringReader(buf));
            transaction = xmlDoc.getRootElement();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ZanyException(ZanyErrorMsg.ERR_DEFAULT, "返回报文转化成xml文档失败！\n"+e.getMessage(),e);
        }
        
        Element tmpEle = null, parentEme = null, eMxUnit = null, childEme = null;
        Map tmpMap = tmpMap = new HashMap();;
        tmpEle = transaction;
        List tmpList = tmpEle.getChildren();
        if ((tmpList != null) && (!tmpList.isEmpty())) {
        	for (int i = 0; i < tmpList.size(); i++) {
        		eMxUnit = (Element) tmpList.get(i);
        		List child = eMxUnit.getChildren();
        		if ((child != null) && (!child.isEmpty())) {
	                for (int j = 0; j < child.size(); j++) {
	                    childEme = (Element) child.get(j);
	                    String name = childEme.getName();
	                    String value = childEme.getText();
	                    tmpMap.put(name, value);
	                }
        		}
        	}
        }
        return tmpMap;
	}
	
	public Map<String,Object> getReturnHeaderMap(Map<String, String> headerMap, Map<String, String> statusMap){
		Map<String,Object> returnHeader = new HashMap<String,Object>();
		Map<String,Object> returnMsg = new HashMap<String,Object>();
		returnMsg.put("msgCd", headerMap.get("msgCd").substring(0, 9)+"1");
		returnMsg.put("sndAppCd", "HOUSE");
		returnMsg.put("sndMbrCd", "HOUSE");
		returnMsg.put("sndDt", DateFormater.getSystemCurrentDateSimple());
		returnMsg.put("sndTm", DateFormater.formatDate("hhmmssms"));
		returnMsg.put("rcvAppCd", "BANK");
		returnMsg.put("seqNb", Long.valueOf(headerMap.get("seqNb"))+1l);
		
		returnMsg.put("refSeqNb", headerMap.get("seqNb"));
		returnMsg.put("refMsgCd", headerMap.get("msgCd"));
		returnMsg.put("refSndAppCd", "BANK");
		returnMsg.put("refSndMbrCd", headerMap.get("sndMbrCd"));
		returnMsg.put("refSndDt", headerMap.get("sndDt"));
		returnMsg.put("refSndTm", headerMap.get("sndTm"));
		returnHeader.put("msg", returnMsg);
		returnHeader.put("status", statusMap);
		return returnHeader;
	}
}


